package com.itqf.realm;

import com.itqf.bean.User;
import com.itqf.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * projectName: rbac2103
 *
 * @author: 赵伟风
 * time: 2021/7/9 14:26
 * description:自定义realm
 */
public class AuthorizationRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;


    /**
     * 获取授权信息的方法
     * Subject hasRole/checkRole   isPermissted/checkPermissted
     *
     * 根据账号信息查询所有的角色和权限!装到AuthorizationInfo返回!
     *
     * Retrieves the AuthorizationInfo for the given principals from the underlying data store.  When returning
     * an instance from this method, you might want to consider using an instance of
     * {@link SimpleAuthorizationInfo SimpleAuthorizationInfo}, as it is suitable in most cases.
     *
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return the AuthorizationInfo associated with this principals.
     * @see SimpleAuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //1.获取用户的信息 账号  用户id
        //principals.getPrimaryPrincipal();获取的是 doGetAuthenticationInfo方法 返回的 AuthenticationInfo() 第一个参数! User
        User user = (User) principals.getPrimaryPrincipal();
        //2.查询用户对应的角色和权限
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream("mybatis_config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }



        List<String> roles = userMapper.queryRoles(user.getuId());

        List<String> permissions = userMapper.queryPermissions(user.getuId());


        //3.角色和权限装到AuthorizationInfo
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);


        return authorizationInfo;
    }

    /**
     *
     * 获取认证信息的方法
     *
     * 当Subject调用login方法的时候会触发!
     * 并且会将封装用户输入账号密码token传入到该方法!
     *
     * 我们要做的就是,根据token的账号部分,查询正确的密码返回给securityManager
     *
     * Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
     * authentication token.
     * <p/>
     * For most datasources, this means just 'pulling' authentication data for an associated subject/user and nothing
     * more and letting Shiro do the rest.  But in some systems, this method could actually perform EIS specific
     * log-in logic in addition to just retrieving data - it is up to the Realm implementation.
     * <p/>
     * A {@code null} return value means that no account could be associated with the specified token.
     *
     * @param token the authentication token containing the user's principal and credentials
     * @return an {@link AuthenticationInfo} object containing account data resulting from the
     * authentication ONLY if the lookup is successful (i.e. account exists and is valid, etc.)
     * @throws AuthenticationException if there is an error acquiring data or performing
     *                                 realm-specific authentication logic for the specified <tt>token</tt>
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


        //1.获取token中的账号
        String account = (String) token.getPrincipal(); //输入的账号部分
        //2.拿账号去数据库查询
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream("mybatis_config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        User user = userMapper.queryByAccount(account);

        //3.如果没有查到直接返回Null

        if (user == null) {

            return null;
        }

        //4.如果根据账号查询到了对应的用户 - 只需要返回密码即可

        /**
         * 参数1:账号  认证来说是无用! realm和subject的通道!放在这的在
         *             subject可以读取到!subject.getPrincipal();
         *             doGetAuthorizationInfo(PrincipalCollection principals) principals.getPrimaryPrincipal();
         *
         *
         * 参数2:密码
         * 参数3:盐
         * 参数4:realmname 自定义
         */
        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(user,user.getuPassword(), ByteSource.Util.bytes(user.getuSlat()),"myrealm");

        return info;
    }
}
